package com.rzico.sbl.ui.order

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.amap.api.toAMapRoute
import com.amap.api.toBaiduDirection
import com.amap.api.toTenCentRoute
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDeliverBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.DeliverViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject
import kotlin.math.abs

class DeliverActivity : BaseActivity(R.layout.activity_deliver) {

    private val mBinding by lazy { ActivityDeliverBinding.bind(getRootView()) }
    private var mState = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<DeliverViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initTabLayout()
        initLayout()
        initSearch()
    }

    private fun initTabLayout() {
        val index = intent.getIntExtra("index", 2)

        mBinding
            .deliverTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mState = when (it.position) {
                                0 -> "unconfirmed"
                                1 -> "undispatch"
                                2 -> "dispatch"
                                3 -> "delivery"
                                4 -> "completed"
                                else -> ""
                            }

                            mBinding.apply {
                                (it.position == 2)
                                    .conditionElse(
                                        actionTrue = {
                                            deliverBatchFl.visibleAnimation()
                                            deliverRoute.visibleAnimation()
                                        },
                                        actionFalse = {
                                            deliverBatchFl.goneAnimation()
                                            deliverRoute.goneAnimation()
                                        }
                                    )

                                (userRole in "1,2,10")
                                    .conditionElse(
                                        actionTrue = { deliverBatch.visibleAnimation() },
                                        actionFalse = { deliverBatch.goneAnimation() }
                                    )
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待确认"
                    },
                    index == 1
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待配送"
                    },
                    index == 2
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "配送中"
                    },
                    index == 3
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已送达"
                    },
                    index == 4
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已核销"
                    },
                    index == 5
                )
            }
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyImg.setEmptyImage(
                        resId = R.mipmap.icon_order_no,
                        dpSize = 100f
                    )
                    it.emptyHint.text = "暂无相关运单信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            orderCount()
                            getData(0)
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_time, bean.hint + bean.time)
                                text(R.id.item_order_status, bean.status_hint)

                                clicked {
                                    startActivityEx<DeliverDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "status" to mState,
                                        "shipId" to bean.shipId
                                    )
                                }
                            }
                        }
                        .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                                text(R.id.item_order_price, "")
                                text(R.id.item_order_num, "x${bean.quantity}")

                                visibility(
                                    R.id.item_order_img_label,
                                    visibleValue { bean.first }
                                )

                                with<ImageView>(R.id.item_order_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<ImageView>(R.id.item_order_img_type) {
                                    when (bean.methodDescr) {
                                        "offline" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order03)
                                        }

                                        "eleme", "elemengc" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order04)
                                        }

                                        "meituan" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order05)
                                        }

                                        "nongfu" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order06)
                                        }

                                        "jd" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order10)
                                        }

                                        "taobao" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order11)
                                        }

                                        "pinduoduo" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order12)
                                        }

                                        "dummy" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order22)
                                        }

                                        "ali" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order26)
                                        }

                                        else -> it.gone()
                                    }
                                }

                                with<ImageView>(R.id.item_order_img_status) {
                                    it.gone = bean.hopeDate.isEmpty() && bean.reminderDate.isEmpty()

                                    bean.hopeDate.notEmpty {
                                        it.setImageResource(
                                            conditionIf(
                                                bean.fast,
                                                R.mipmap.icon_order07,
                                                R.mipmap.icon_order02
                                            )
                                        )
                                    }

                                    bean.reminderDate.notEmpty {
                                        it.setImageResource(R.mipmap.icon_order24)
                                    }
                                }

                                clicked {
                                    startActivityEx<DeliverDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "status" to mState,
                                        "shipId" to bean.shipId
                                    )
                                }
                            }
                        }
                        .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_order_count, bean.total_num)
                                gone(R.id.item_order_layout)
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_shop, bean.meituanShopName)
                                text(
                                    R.id.item_order_phone,
                                    when {
                                        userRole in "1,2"
                                                || privacyStatus == "off" -> bean.phone
                                        else -> bean.phone.phoneReplaceWithStar()
                                    }
                                )
                                text(R.id.item_order_addr, bean.address)
                                text(R.id.item_order_done, bean.deliveryDate)
                                text(R.id.item_order_cmemo, bean.cardMemo)
                                text(R.id.item_order_bmemo, bean.memo)
                                text(R.id.item_order_smemo, bean.shipMemo)

                                getView<View>(R.id.item_order_shop_ll)
                                    .isGone = bean.meituanShopName.isEmpty()
                                getView<View>(R.id.item_order_yu_ll).isVisible =
                                    bean.deliveryDate.isEmpty() && bean.estimateDate.isNotEmpty()
                                getView<View>(R.id.item_order_done_ll)
                                    .isGone = bean.deliveryDate.isEmpty()
                                getView<View>(R.id.item_order_cmemo_ll)
                                    .isGone = bean.cardMemo.isEmpty()
                                getView<View>(R.id.item_order_bmemo_ll)
                                    .isGone = bean.memo.isEmpty()
                                getView<View>(R.id.item_order_smemo_ll)
                                    .isVisible = bean.shipMemo.isNotEmpty()
                                        && mState in "unconfirmed,undispatch,dispatch"

                                with<TextView>(R.id.item_order_yu) {
                                    val diffTime = getDiffTime(bean.estimateDate)

                                    var timeSpace = getString("orderWarn").intValue
                                    if (timeSpace == 0) timeSpace = 30

                                    when {
                                        diffTime > 0 && bean.status in "unconfirmed/undispatch/dispatch" -> {
                                            it.setTextColor(getColorEx(R.color.red))
                                            it.text =
                                                "${bean.estimateDate.getTimeString()}\n已超时${
                                                    formatTime(diffTime)
                                                }"
                                        }

                                        diffTime in timeSpace * -1 * 60 * 1000..0
                                                && bean.status in "unconfirmed/undispatch/dispatch" -> {
                                            it.setTextColor(getColorEx(R.color.orange))
                                            it.text = "${bean.estimateDate.getTimeString()}\n${
                                                formatTime(abs(diffTime))
                                            }后超时"
                                        }

                                        else -> {
                                            it.setTextColor(getColorEx(R.color.black))
                                            it.text = bean.estimateDate.getTimeString()
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_pei) { tv ->
                                    tv.text =
                                        "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                    tv.isGone = bean.adminName.isEmpty()
                                }

                                with<TextView>(R.id.item_order_btn1) {
                                    it.text = bean.hint_btn1
                                    it.isGone = bean.hint_btn1.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unconfirmed" -> {
                                                when (userRole) {
                                                    // 运单派单
                                                    "1", "2", "10" ->
                                                        startActivityEx<DeliverSendActivity>(
                                                            "mode" to "unconfirmed",
                                                            "orderSn" to bean.orderSN,
                                                            "shippingSn" to bean.shippingSn
                                                        )
                                                    // 运单抢单
                                                    "3" -> if (bean.allowRob) grabOrder(bean.shippingSn)
                                                }
                                            }
                                            // 开始配送
                                            "undispatch" -> dispatchOrder(bean.shippingSn)
                                            // 运单送达
                                            "dispatch" ->
                                                startActivityEx<DeliverDispatchActivity>(
                                                    "shipId" to bean.id,
                                                    "shippingSn" to bean.shippingSn
                                                )
                                            // 运单审核
                                            "delivery" ->
                                                startActivityEx<DeliverReviewActivity>(
                                                    "shipId" to bean.id,
                                                    "shippingSn" to bean.shippingSn
                                                )
                                            // 工资结算
                                            "completed" -> salaryOrder(index, bean.shippingSn)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn2) {
                                    it.text = bean.hint_btn2
                                    it.isGone = bean.hint_btn2.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            // 取消派单
                                            "unconfirmed" -> cancelOrder(bean.orderSN)
                                            // 一键导航
                                            "dispatch" ->
                                                (bean.lat.isNotEmpty() && bean.lng.isNotEmpty())
                                                    .condition {
                                                        when {
                                                            isAvilible("com.autonavi.minimap") -> {
                                                                toAMapRoute(
                                                                    sourceApplication = getString(R.string.app_name),
                                                                    t = "3",
                                                                    rideType = "elebike",
                                                                    dlat = bean.lat,
                                                                    dlon = bean.lng
                                                                )
                                                            }

                                                            isAvilible("com.baidu.BaiduMap") -> {
                                                                toBaiduDirection(
                                                                    destination = "${bean.lat},${bean.lng}",
                                                                    src = "com.rzico.sbl",
                                                                    mode = "riding",
                                                                    coord_type = "gcj02"
                                                                )
                                                            }

                                                            isAvilible("com.tencent.map") -> {
                                                                toTenCentRoute(
                                                                    type = "bike",
                                                                    tocoord = "${bean.lat},${bean.lng}"
                                                                )
                                                            }

                                                            else -> showToast("请安装地图软件！")
                                                        }
                                                    }
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn3) {
                                    it.text = bean.hint_btn3
                                    it.isGone = bean.hint_btn3.isEmpty()

                                    // 运单驳回
                                    it.oneClick { rejectOrder(bean.shippingSn) }
                                }

                                clicked {
                                    startActivityEx<DeliverDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "status" to mState,
                                        "shipId" to bean.id
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .searchLayout
            .apply {
                searchEdit.hint = "请输入收货人、电话、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        searchEdit.text.isBlank()
                            .conditionElse(
                                actionTrue = { showToast("请输入收货人、电话、地址") },
                                actionFalse = {
                                    mKeyWord = searchEdit.textTrim
                                    updateList()
                                }
                            )
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text.isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入收货人、电话、地址") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mBinding
            .deliverBatch
            .oneClick {
                startActivityEx<DeliverBatchActivity>()
            }

        mBinding
            .deliverRoute
            .oneClick {
                startActivityEx<DeliverRouteActivity>()
            }

        observe<String>("deliverList") {
            getViewModel()
                .delay { updateList() }
        }
    }

    /**
     * 运单抢单
     */
    private fun grabOrder(orderSN: String) {
        showHintDialog(
            title = "抢单",
            hint = "确定要抢该订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.deliveryGrb, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        isFailed = false,
                        onSuccess = {
                            showToast("抢单成功！")
                            // 刷新列表
                            updateList()
                        },
                        onFailed = { code, message ->
                            (code == "warn")
                                .conditionElse(
                                    actionTrue = {
                                        showOneHintDialog(
                                            hint = message,
                                            isForced = true,
                                            onResult = { updateList() }
                                        )
                                    },
                                    actionFalse = { showToast(message) }
                                )
                        }
                    )
            }
        )
    }

    /**
     * 运单取消派单
     */
    private fun cancelOrder(orderSN: String) {
        showHintDialog(
            title = "派单驳回",
            hint = "确定要取消派单并驳回吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.deliveryCan, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("派单驳回成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 运单开始派单
     */
    private fun dispatchOrder(orderSN: String) {
        getViewModel()
            .operateOrder(BaseUrl.deliveryCfm, orderSN)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("操作成功！")

                    updateList()
                }
            )
    }

    /**
     * 运单驳回
     */
    private fun rejectOrder(orderSN: String) {
        showMemoDialog(
            title = "运单驳回",
            hint = "请输入驳回原因",
            inputType = "longText",
            canEmpty = false
        ) {
            getViewModel()
                .requestBind(
                    isMultipart = true,
                    requestUrl = BaseUrl.deliveryBak,
                    params = arrayOf(
                        "sn" to orderSN,
                        "memo" to it
                    )
                )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeBySuccess(
                    event = getViewModel(),
                    onSuccess = {
                        showToast("运单驳回成功！")

                        updateList()
                    }
                )
        }
    }

    /**
     * 工资结算
     */
    private fun salaryOrder(index: Int, shippingSN: String) {
        showSalaryDialog(
            isForced = true,
            onSure = { value ->
                getViewModel()
                    .salaryOrder(shippingSN, value)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("工资结算提交成功！")

                            (mList[index] as OrderFooter).apply {
                                freight = value
                                hint_btn1 = "工资: ${freight.formatDecimal()} 元"
                            }

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        )
    }

    /**
     * 更新自定义Tab数量
     */
    private fun orderCount() {
        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    getViewModel()
                        .updateNum(
                            obj.optNotNull("unconfirmed"),
                            obj.optNotNull("undispatch"),
                            obj.optNotNull("confirmed"),
                            mBinding.deliverTab
                        )
                }
            )
    }

    /**
     * 运单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .deliverList(
                page = index,
                keyWord = mKeyWord,
                userId = getString("uid"),
                roleId = userRole,
                serviceId = serviceId,
                state = mState,
                onSuccess = {
                    mList.apply {
                        (index == 0).condition {
                            clear()
                            pageNum = 0
                        }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        orderCount()
        getData(0)
    }

}